package dao

import (
	"context"
	"fmt"
	"order_srv/basic/config"
	"order_srv/handler/models"
	"time"

	"gorm.io/gorm"
)

// CreateOrderPayment 创建支付记录
func CreateOrderPayment(ctx context.Context, payment *models.OrderPayment) error {
	// 参数校验
	if payment.OrderID == 0 {
		return fmt.Errorf("订单ID不能为空")
	}
	if payment.Amount <= 0 {
		return fmt.Errorf("支付金额必须大于0")
	}
	if payment.PaymentType == 0 || payment.PaymentMethod == 0 {
		return fmt.Errorf("支付类型和支付方式不能为空")
	}

	// 生成支付单号
	payment.PaymentNo = generatePaymentNo()

	err := config.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		// 1. 创建支付记录
		if err := tx.Create(payment).Error; err != nil {
			return fmt.Errorf("创建支付记录失败: %w", err)
		}

		// 2. 记录支付状态日志
		statusLog := &models.OrderStatusLog{
			OrderID:      payment.OrderID,
			FromStatus:   -1, // 初始状态
			ToStatus:     0,  // 待支付
			StatusType:   2,  // 2-支付状态
			OperatorID:   "system",
			OperatorType: 4, // 4-系统
			Reason:       "创建支付记录",
			Remark:       fmt.Sprintf("创建支付单号: %s, 金额: %.2f", payment.PaymentNo, payment.Amount),
		}
		if err := tx.Create(statusLog).Error; err != nil {
			return fmt.Errorf("记录支付状态日志失败: %w", err)
		}
		return nil
	})

	if err != nil {
		return err
	}
	return nil
}

// UpdatePaymentStatus 更新支付状态
func UpdatePaymentStatus(ctx context.Context, paymentID uint64, status int8, transactionID, failureReason string) error {
	// 参数校验
	if paymentID == 0 {
		return fmt.Errorf("支付ID不能为空")
	}
	if status < 0 || status > 4 {
		return fmt.Errorf("无效的支付状态")
	}

	return config.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		// 1. 获取支付记录
		var payment models.OrderPayment
		if err := tx.First(&payment, paymentID).Error; err != nil {
			return err
		}

		// 2. 更新支付状态
		updates := map[string]interface{}{
			"payment_status": status,
		}
		if transactionID != "" {
			updates["transaction_id"] = transactionID
		}
		if status == 1 { // 已支付
			updates["paid_at"] = time.Now()
		} else if status == 3 { // 已退款
			updates["refunded_at"] = time.Now()
		}
		if failureReason != "" {
			updates["failure_reason"] = failureReason
		}

		if err := tx.Model(&models.OrderPayment{}).Where("id = ?", paymentID).Updates(updates).Error; err != nil {
			return err
		}

		// 3. 更新订单支付状态和金额
		if status == 1 { // 已支付
			if err := tx.Model(&models.Order{}).Where("id = ?", payment.OrderID).Updates(map[string]interface{}{
				"payment_status": 1, // 已支付
				"paid_amount":    gorm.Expr("paid_amount + ?", payment.Amount),
			}).Error; err != nil {
				return err
			}
		} else if status == 3 { // 已退款
			if err := tx.Model(&models.Order{}).Where("id = ?", payment.OrderID).Updates(map[string]interface{}{
				"payment_status": 3, // 已退款
				"refund_amount":  gorm.Expr("refund_amount + ?", payment.Amount),
			}).Error; err != nil {
				return err
			}
		}

		// 4. 记录状态变更日志
		statusLog := &models.OrderStatusLog{
			OrderID:      payment.OrderID,
			FromStatus:   payment.PaymentStatus,
			ToStatus:     status,
			StatusType:   2, // 支付状态
			OperatorID:   "system",
			OperatorType: 4, // 系统
			Reason:       "支付状态更新",
			Remark:      fmt.Sprintf("支付状态从%d更新为%d", payment.PaymentStatus, status),
		}
		return tx.Create(statusLog).Error
	})
}

// 业务逻辑辅助函数

// generatePaymentNo 生成支付单号
func generatePaymentNo() string {
	return fmt.Sprintf("PAY%d", time.Now().UnixNano())
}